import { getInfoAPI, loginAPI, logoutAPI } from '@/api/manager'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { removeToken } from '@/composables/auth'
import { router } from '@/router'

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const user = ref({})
  const SET_USERINFO = (userValue) => {
    user.value = userValue
  }
  const getInfo = async () => {
    // 获取当前登录用户信息
    const res = await getInfoAPI()

    // console.log(res)
    SET_MENUS(res.menus)
    SET_RULENAMES(res.ruleNames)
    SET_USERINFO(res)
  }

  const logout = async () => {
    const res = await logoutAPI()
    // console.log(res)
    // 移除cookie里的token
    removeToken()
    // 清除当前用户状态pinia
    SET_USERINFO({})
    // 跳转到登录页
    router.push('/login')
  }

  // 侧边宽度
  const asideWidth = ref('250px')
  // 展开/缩起侧边
  const handleAsideWidth = () => {
    asideWidth.value = asideWidth.value === '250px' ? '64px' : '250px'
  }

  const menusList = ref([])
  const ruleNames = ref([])
  const SET_MENUS = (menus) => {
    menusList.value = menus
  }
  const SET_RULENAMES = (rulename) => {
    ruleNames.value = rulename
  }
  return {
    user,
    SET_USERINFO,
    getInfo,
    logout,
    asideWidth,
    handleAsideWidth,
    menusList,
    ruleNames,
    SET_MENUS,
    SET_RULENAMES,
  }
})
